package com.shop.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.entity.pojo.*;
import com.shop.user.mapper.CostMapper;
import com.shop.user.mapper.StyleMapper;
import com.shop.user.service.CostService;
import com.shop.utils.common.enums.Code;
import com.shop.utils.common.enums.Message;
import com.shop.utils.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class CostServiceImpl extends ServiceImpl<CostMapper, Cost> implements CostService {

    @Autowired
    private CostMapper costMapper;
    @Autowired
    private StyleMapper styleMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Result<List<Cost>> getStyleCost(Long styleId) {
        log.info("用户-获取商品款式的价格");
        long start = System.currentTimeMillis();
        if (styleId==null) {
            log.info("styleId==null");
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        String key=Message.WeChat_Key_Cost+styleId;
        Map costList = redisTemplate.opsForHash().entries(key);
        Long check = redisTemplate.opsForHash().size(key);
        if (check!=0) {
            log.info("浏览缓存");
            return Result.okResult(costList);
        }
        log.info("浏览数据库");
        List<Cost> costs = costMapper.selectList(Wrappers.<Cost>lambdaQuery().eq(Cost::getStyleId, styleId).eq(Cost::getState,Message.Put));
        if (CollectionUtils.isEmpty(costs)||costs.size()==Message.Check_Int_Null) {
            long end = System.currentTimeMillis();
            log.info("用户在缓存中获取某个款式价格进程完成，总耗时:{}",(end-start));
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        Style style = styleMapper.selectById(styleId);
        String images=style.getStyleImages();
        Map<String,Object> map=new HashMap<>();
        map.put("costList",costs);
        map.put("images",images);
//        redisTemplate.opsForValue().set(key,map);
        redisTemplate.opsForHash().putAll(key,map);
        long end = System.currentTimeMillis();
        log.info("用户在数据库获取某个款式价格进程完成，总耗时:{}",(end-start));
        return Result.okResult(map);
    }

}
